using UnityEngine;
using Yoozoo.Libs;

namespace Gameplay.PVE.TurnBase
{
    public class FloatComponent : IComponent,ITransmit
    {
        private float friction = 1;
        private float maxFlyHeight = 1f;
        void IClass.OnReset()
        {

        }
        private BattleUnit unit;
        void IComponent.OnInitialize(BattleUnit unit)
        {
            this.unit = unit;
        }

        void IComponent.OnUpdate()
        {
            if (unit.Data.isFloating && unit.Data.velocity.y < 0)
            {
                unit.Data.isFloating = false;
                TurnBaseManager.Instance.UpdateTbsFocus(0.5f);
            }
        }

        void IComponent.OnBirth()
        {
            
        }
        
        void IComponent.OnDead()
        {
            
        }
        
        void ITransmit.OnTransmit(ETransmitType type, BaseTransmitArg arg)
        {
            if (type == ETransmitType.HitFloat)
            {
                var hitArg = arg as HitFloatArg;

                /*if (unit.Data.velocity.y < velocityY)
                {
                    unit.Data.velocity.y = velocity;
                }*/
                Vector3 velocityBase = (unit.Data.position - hitArg.source.Data.position).normalized * hitArg.velocity.x;//(unit.Data.position - hitArg.source.Data.position).x;
                float y = Mathf.Max(unit.Data.velocity.y, hitArg.velocity.y);
                var velocity = velocityBase + new Vector3(0,y,0);
                float flyHeight = velocity.y * velocity.y / 2f / GravityComponent.gravity;

                float limitedHeight = maxFlyHeight - unit.Data.position.y;
                
                if (flyHeight > limitedHeight)
                {
                    velocity.y = Mathf.Sqrt(limitedHeight * 2 * GravityComponent.gravity);
                }
                unit.Data.velocity = velocity;
                unit.Data.floatingPosition = unit.Data.position + new Vector3(0, flyHeight, 0);
                unit.Data.isFloating = true;
                TurnBaseManager.Instance.UpdateTbsFocus();
            }
        }
    }
}